import { openMessage } from "@/hy_dev_lib/src";
import { dispatchPubsub } from "@/hy_dev_lib/src/store";
import Cookies from "js-cookie";

// import { config } from 'react-transition-group'

const TokenKey = "TOKEN";
// const UserKey = Config.UserKey;
// const MenuKey = Config.MenuKey;
// const RouteKey = Config.RouteKey;
// const PowerKey = Config.PowerKey;

const EXPIRESTIME = 2 * 3600 * 1000;

/**
 * 获取当前时间的2个小时后
 * @returns 两小时后的时间
 */
export function getExpiresTime() {
  const millisecond = new Date().getTime();
  const expiresTime = new Date(millisecond + EXPIRESTIME);
  return expiresTime;
}

/**
 * 获取保存的 'Bearer' + Token
 * @returns Token字符串
 */
export function getToken() {
  return "Bearer " + getTokenCookies();
}
/**
 * 获取保存的Token
 */
export function getTokenCookies() {
  return Cookies.get(TokenKey) || "";
}
/**
 * 保存Token
 * @param {*} token
 */
export function saveToken(token: string) {
  if (/.*[\u4e00-\u9fa5]+.*$/.test(token)) return;
  Cookies.set(TokenKey, token, { expires: getExpiresTime() });
}

/**
 * 清空token
 */
export const clearToken = () => {
  Cookies.remove(TokenKey);
  Cookies.remove("WebId");
  Cookies.remove("Clientid");
  Cookies.remove("showSystemConfigMenu");
  // localStorage.removeItem("refreshToken");
  // localStorage.removeItem("tokenTime");
};

export function setWebId(webid: string) {
  Cookies.set("WebId", webid, { expires: getExpiresTime() });
}

export function getWebId() {
  return Cookies.get("WebId");
}

export const logout = () => {
  dispatchPubsub("STOP_SIGNAL_R_CONNECTION", {});
  if (location.hash.includes("wecom")) {
    return openMessage({
      content: "已退出！",
      duration: 0,
    });
  }
  setTimeout(() => {
    clearToken();
    if (location.hash !== "#/login") {
      window.location.href = "/#/login";
    }
  }, 300);
};

// 获取客户端id
export function getClientId() {
  let Clientid = Cookies.get("Clientid");
  if (!Clientid) {
    Clientid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
    Cookies.set("Clientid", Clientid);
  }
  return Clientid;
}
